import { useRouter } from "next/router";
import { QueryClient, useQuery } from 'react-query';
import { dehydrate } from 'react-query/hydration'
import CourseChapterLayout from "@/components/course-chapter-layout";
import Article from "@/components/article";
import { getCourseById } from "@/apis/course";
import { getChapters, getChapterText } from "@/apis/chapter";
import { isCourseManager } from "@/tools/data-helpers";


export default function ChapterHomePage() {
    const { courseId, chapterId } = useRouter().query;


    const { data: course } = useQuery(['course', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId)
    });
    const { data: chapters } = useQuery(['chapters', courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getChapters(courseId);
    });

    const { data: chapterText } = useQuery(['chapterText', chapterId], ({ queryKey }) => {
        const [_key, chapterId] = queryKey;
        return getChapterText(chapterId);
    });

    let previousId = null;
    let nextId = null;
    for (let i = 0; i < chapters.length; i++) {
        if (parseInt(chapters[i].id) === parseInt(chapterId)) {
            if (i > 0) {
                previousId = chapters[i - 1].id;
            }
            nextId = chapters[i].next_id;
            break;
        }
    }

    const previousLink = `/course/${courseId}/chapter/${previousId}`;
    const nextLink = `/course/${courseId}/chapter/${nextId}`;

    return (
        <CourseChapterLayout course={course} chapters={chapters} courseId={courseId}>
            <Article courseId={courseId} content={chapterText && chapterText.content} isCourseManager={isCourseManager(course && course.manager)} id={chapterText && chapterText.id} isIntroduction={false} previousLink={previousId && previousLink} nextLink={nextId && nextLink} />
        </CourseChapterLayout>
    );
}

export async function getServerSideProps({ query }) {
    const queryClient = new QueryClient();

    await queryClient.prefetchQuery(['course', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getCourseById(courseId);
    });
    await queryClient.prefetchQuery(['chapters', query.courseId], ({ queryKey }) => {
        const [_key, courseId] = queryKey;
        return getChapters(courseId);
    });
    await queryClient.prefetchQuery(['chapterText', query.chapterId], ({ queryKey }) => {
        const [_key, chapterId] = queryKey;
        return getChapterText(chapterId);
    });

    return {
        props: {
            dehydratedState: dehydrate(queryClient),
        },
    }
}
